package com.dxd.onlineshop.service.impl;

import com.dxd.onlineshop.mapper.AddressMapper;
import com.dxd.onlineshop.pojo.Address;
import com.dxd.onlineshop.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AddressServiceImpl implements AddressService {

    private final AddressMapper addressMapper;
    private static final int MAX_ADDRESSES = 5;

    @Autowired
    public AddressServiceImpl(AddressMapper addressMapper) {
        this.addressMapper = addressMapper;
    }

    @Override
    public List<Address> getUserAddresses(Long userId) {
        return addressMapper.findByUserId(userId);
    }

    @Override
    public Address getAddress(Long id) {
        return addressMapper.findById(id);
    }

    @Override
    @Transactional
    public void addAddress(Address address) throws Exception {
        int count = addressMapper.countByUserId(address.getUserId());
        if (count >= MAX_ADDRESSES) {
            throw new Exception("已达到最大地址数量限制");
        }

        if (address.isDefault() || count == 0) {
            // 如果新地址被设置为默认，或者这是用户的第一个地址
            addressMapper.resetDefaultForUser(address.getUserId());
            address.setDefault(true);
        }

        addressMapper.insert(address);
    }

    @Override
    @Transactional
    public void updateAddress(Long userId, Address address) throws Exception {
        Address existingAddress = addressMapper.findById(address.getId());
        if (existingAddress == null || !existingAddress.getUserId().equals(userId)) {
            throw new Exception("地址不存在或不属于该用户");
        }

        address.setUserId(userId); // 确保不会修改用户ID

        if (address.isDefault()) {
            // 如果更新后的地址被设置为默认，则重置其他地址
            addressMapper.resetDefaultForUser(userId);
        } else if (existingAddress.isDefault() && !address.isDefault()) {
            // 如果之前是默认地址，但现在取消了默认状态，需要设置另一个地址为默认
            List<Address> otherAddresses = addressMapper.findByUserId(userId).stream()
                    .filter(a -> !a.getId().equals(address.getId()))
                    .collect(Collectors.toList());
            if (!otherAddresses.isEmpty()) {
                Address newDefault = otherAddresses.get(0);
                addressMapper.updateDefaultStatus(userId, newDefault.getId(), true);
            }
        }

        addressMapper.update(address);
    }

    @Override
    @Transactional
    public void deleteAddress(Long userId, Long id) throws Exception {
        Address address = addressMapper.findById(id);
        if (address == null || !address.getUserId().equals(userId)) {
            throw new Exception("地址不存在或不属于该用户");
        }

        addressMapper.delete(id);

        if (address.isDefault()) {
            Address newDefault = addressMapper.findByUserId(userId).stream()
                    .findFirst()
                    .orElse(null);

            if (newDefault != null) {
                addressMapper.updateDefaultStatus(userId, newDefault.getId(), true);
            }
        }
    }

    @Override
    @Transactional
    public void setDefaultAddress(Long userId, Long addressId) throws Exception {
        Address address = addressMapper.findById(addressId);
        if (address == null || !address.getUserId().equals(userId)) {
            throw new Exception("地址不存在或不属于该用户");
        }

        // 将该用户的所有地址设置为非默认
        addressMapper.resetDefaultForUser(userId);

        // 将指定地址设置为默认
        addressMapper.updateDefaultStatus(userId, addressId, true);
    }

    @Override
    public int getAddressCount(Long userId) {
        return addressMapper.countByUserId(userId);
    }


}